package com.data.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.config.dao.EquStateConfigDao;
import com.config.dao.EquipmentDao;
import com.config.dao.LineConfigDao;
import com.config.entity.EquStateConfig;
import com.config.entity.Equipment;
import com.config.entity.LineConfig;
import com.data.dao.StateDayDao;
import com.data.dao.StateMonthDao;
import com.data.entity.StateDay;
import com.data.entity.StateMonth;

@Service("stateMonthService")
public class StateMonthServiceImpl implements StateMonthService{
	@Resource(name="lineConfigDao")
	private LineConfigDao lineConfigDao;
	@Resource(name="equipmentDao")
	private EquipmentDao equipmentDao;
	@Resource(name="stateMonthDao")
	private StateMonthDao stateMonthDao;
	@Resource(name="stateDayDao")
	private StateDayDao stateDayDao;
	@Resource(name="equStateConfigDao")
	private EquStateConfigDao equStateConfigDao;
	/**
	 * 根据时间提取设备状态月记录
	 * @param belongDate
	 */
	@Override
	public void saveStateMonth(Date belongDate) {
		SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		List<LineConfig> lines=lineConfigDao.findAllLine();
		List<EquStateConfig> states=equStateConfigDao.findAll();
		if(lines.size()!=0){
			for(LineConfig line:lines){
				List<Equipment> equs=equipmentDao.listByLine(line.getId());
				if(equs.size()!=0){
					for(Equipment e:equs){
						if(states.size()!=0){
							for(EquStateConfig state:states){
								//查询设备月状态记录，不存在则保存，存在则更新
								StateMonth month=stateMonthDao.getStateMonthByDate(e.getId(), state.getStateType(), sdf.format(belongDate));
								boolean isNew=false;
								if(month==null){
									month=new StateMonth();
									month.setEquId(e.getId());
									month.setBelongDate(sdf.format(belongDate));
									month.setStateType(state.getStateType());
									isNew=true;	
								}
								Calendar  cal=Calendar.getInstance();
								cal.setTime(belongDate);
								String startDate=sdf.format(cal.getTime())+"-"+"01";//每月从1号开始计算
								String endDate=sdft.format(belongDate);
								//计算从开始到结束日期的总持续时间和电度
								List<StateDay> days=stateDayDao.getStateDays(e.getId(), state.getStateType(), startDate, endDate);
								double duration=0.0; double relativeComp=0.0;
								if(days.size()!=0){
									for(StateDay day:days){
										duration+=day.getDuration();
										relativeComp+=day.getRelativeComp();
									}
								}
								month.setRelativeComp(relativeComp);
								month.setDuration(duration);
								if(isNew){
									stateMonthDao.save(month);
								}else{
									stateMonthDao.update(month);
								}
							}
						}
					 }
				}
			}
		}
	}
}
